package top.hkyzf.study.leetcode.array;

import org.junit.Test;

import java.util.Arrays;

/**
 * @author 朱峰
 * @date 2022-2-24 10:28
 */
public class 球会落何处_1706 {
    public int[] findBall(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[][] dp = new int[m+1][n];
        // 初始化球位置
        for (int i = 0; i < n; i++) {
            dp[0][i] = i;
        }
        // 开始向下滚动
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                // 上一轮小球的位置
                int pre = dp[i][j];
                // 如果上次状态是 -1，这次状态也是 -1
                if (pre == -1) {
                    dp[i+1][j] = pre;
                    continue;
                }
                if (grid[i][pre] > 0 && pre == n-1) {
                    dp[i+1][j] = -1;
                } else if (grid[i][pre] < 0 && pre == 0) {
                    dp[i+1][j] = -1;
                } else if (grid[i][pre] > 0 && grid[i][pre+1] < 0) {
                    dp[i+1][j] = -1;
                } else if (grid[i][pre] < 0 && grid[i][pre-1] > 0) {
                    dp[i+1][j] = -1;
                } else {
                    dp[i+1][j] = pre + grid[i][pre];
                }
            }
        }
        return dp[m];
    }

    @Test
    public void testFindBall () {
        int[][] grid = {{1,1,1,-1,-1},{1,1,1,-1,-1},{-1,-1,-1,1,1},{1,1,1,1,-1},{-1,-1,-1,-1,-1}};
        int[] ball = findBall(grid);
        System.out.println(Arrays.toString(ball));
    }
}
